errors = require('../errors')
UserService = require('../service/UserService')

exports.toSignIn = ->
    src = @query?.src || ''
    this.render 'sign-in', {src}
    yield return

exports.toSignUp = ->
    this.render 'sign-up'
    yield return

exports.gSignIn = ->
    body = @request.body
    this.checkBody('username').optional().notEmpty().len(2, 20, "用户名长度在2-20位");
    this.checkBody('password').optional().notEmpty().len(6, 20, "密码必须在6-20位");

    yield return throw new errors.UserError(this.errors) if this.errors

    username = body.username
    password = body.password
    r = yield from UserService.gSignIn(username, password)

    this.cookies.set('user_id', r._id, {signed: true, httpOnly: true})

    callBackUrl = @query.src || '/'
    this.redirect(callBackUrl)

exports.gSignUp = ->
    body = @request.body
    this.checkBody('username').optional().notEmpty().len(2, 20, "用户名长度在2-20位");
    this.checkBody('password').optional().notEmpty().len(6, 20, "密码必须在6-20位");

    yield return throw new errors.UserError(this.errors) if this.errors

    yield from UserService.gCreateUser(body)

    this.redirect('/sign-in')

exports.gSignOut = ->
    console.log @state.userId
    delete @state.userId
    this.cookies.set('user_id', null, {signed: true, httpOnly: true})
    this.redirect('/')
    yield return